<?php
/**
 * @author coldarmy
 * 待办事项每日提醒
 */
apf_require_class('Oa_Job_Abstract');
apf_require_class('Const_Flow');
apf_require_class('Bll_Flow_Info');
apf_require_class('Bll_Flow_Role');
apf_require_class('Bll_Flow_ApplyRelation');
apf_require_class('Tools_SendMail');
class Oa_Job_Flow_WaitTodoRemind extends Oa_Job_Abstract {

    private $read_db = "hroa_master";//读数据库
    private $writedb = "hroa_master";//写数据库
    private $bll_role = "";//角色bll
    private $cities = array();
    private $flowtype = array();
    private $userinfo = array();
    private $basedomain = '';

    public function run($mail,$speople){
        $this->log("每日待办事项邮件提醒--开始 ".date('Y-m-d H:i:s'));
        $mail = $this->_check_mail($mail);

        $start_time = microtime(true);
        //当天是否为工作日
        $this->_is_work_day();
         //获取所有代办事项
        $allthings = $this->_get_all_wait_todo();
        if (empty($allthings)) {
            $this->log("今天没有待办事项需要邮件通知！");
            die();
        }
        $this->userinfo = $this->_build_user_info($allthings);
        $bll = new Bll_Flow_Info();
        $this->bll_role = new Bll_Flow_Role();
        $this->bll_rela = new Bll_Flow_ApplyRelation();
        $this->cities= $this->_get_city_list();
        $this->flowtype = $this->_get_flow_type();
        $this->basedomain = 'http://home.corp.anjuke.com';
        $and = '';
        if (!empty($speople) && is_numeric($speople)) {
            $and = " AND user_id = $speople ";
        }
        $startid = 0;
        $limit = 100;
        $sql = "SELECT user_id,user_name,work_city_id,office_mail FROM user where job_status = ? {$and} AND user_id > ? limit $limit";
        //获取所有员工ID
        while (true) {
            $tmp = $this->get_db_rows($sql, $this->read_db, array(1,$startid));
            if(empty($tmp)) {
                break;
              }
            $count = count($tmp);
            $startid = $tmp[$count - 1]['user_id'];
            //根据员工ID获取对应的代办事项
            foreach ($tmp as $key => $val) {
                $params['user_id'] = $val['user_id'];
                $params['role_list'] = $this->_get_role_list($val['user_id'],$val['work_city_id']);
                $waitlist = $bll->get_all_flow_list($params, 10000,0,$allthings);
                if ($waitlist['count'] <= 0) {
                    continue;
                  }
                if ($mail == 'online') {
                    $smail = $val['office_mail'];
                } else {
                    $smail = $mail;
                  }
                $this->log("正在给 {$val['user_name']} 的邮箱 {$smail} 发送邮件......");
                $mailcontent = $this->_build_mail_template($waitlist,$val['user_name']);
                Tools_SendMail::get_instance()->send($smail,date('Y-m-d').'日未处理待办事项',$mailcontent);
            }
        }

        $this->log("每日待办事项邮件提醒--结束 ".date('Y-m-d H:i:s'));
        $this->log("共耗时：".microtime(true) - $start_time);
    }

    private function _check_mail($mail){
        if (empty($mail)) {
            $this->log("即使是测试，你也得给我个邮箱嘛！");
            die();
        } elseif ($mail == 'online') {
            return 'online';
        } elseif (!preg_match("#^([a-zA-Z0-9_\.\-])+@\w+([-.]\w+)*\.\w+([-.]\w+)*$#",$mail)) {
            $this->log("好说歹说，你总得给我个正确的邮箱啊！");
            die();
        } else {
            return $mail;
        }

    }

    /**
     * 如果非工作日，结束Job
     */
    private function _is_work_day() {
        apf_require_class('Tools_Tools');
        $workday = Tools_Tools::get_instance()->actual_work_day_by_month_list(date('Ym'));
        $day = date('Ymd');
        if (in_array($day, $workday)) {
            return;
        } else {
            $this->log("今天非工作日，无需提醒!");
            die();
        }
    }

    /**
     * 用户职位数据,取出页面中可以显示的用户字段信息
     * @param array $datalist
     * @return
     */
    private function _build_user_info($datalist){
        if(empty($datalist)){
            return array();
        }
        $uids = $tmp_uids = $new_uids = array();
        $user_data = array();
        $is_transfer = $is_dimission = 0;
        foreach ($datalist as $val){
            if($val['flow_type']==1){
                $new_uids[$val['user_id']] = $val['flow_id'];
            }else{
                if($val['flow_type']==3){
                    $is_dimission = 1;
                }elseif($val['flow_type']==5){
                    $is_recruit = 1;
                }elseif($val['flow_type']==2 || $val['flow_type']==4){
                    $is_transfer = 1;
                }elseif($val['flow_type']==6 ){
                    $is_regular = 1;
                }elseif($val['flow_type']==7){
                    $is_renew = 1;
                }
                $tmp_uids[$val['flow_id']] = $val['user_id'];
            }
        }
        $job_ids = array();
        if($is_dimission){//是否有离职信息
            apf_require_class('Bll_Flow_Dimission');
            $bll_dimiss = new Bll_Flow_Dimission();
            $d_flow_ids = array_keys($tmp_uids);
            $dimiss = $bll_dimiss->find_by_flow_ids($d_flow_ids);
            foreach($tmp_uids as $flow_id=>$uid){
                if(!empty($dimiss[$flow_id])){
                    $job_ids[$flow_id] = $dimiss[$flow_id]['job_id'];
                }
            }
        }
        if($is_transfer){//是否有转岗信息
            apf_require_class('Bll_Flow_Transfer');
            $bll_tran = new Bll_Flow_Transfer();
            $t_flow_ids = array_keys($tmp_uids);
            $tran = $bll_tran->find_by_ids($t_flow_ids);
            foreach($tmp_uids as $flow_id=>$uid){
                if(!empty($tran[$flow_id])){
                    $job_ids[$flow_id] = $tran[$flow_id]['old_job_id'];
                }
            }
        }

        if($is_recruit){
            apf_require_class('Bll_Flow_Recruit');
            $bll_recruit = new Bll_Flow_Recruit();
            $r_flow_ids = array_keys($tmp_uids);
            $recruit = $bll_recruit->get_recruit_by_ids($r_flow_ids);
            foreach($tmp_uids as $flow_id=>$uid){
                if(!empty($recruit[$flow_id])){
                    $job_ids[$flow_id] = $recruit[$flow_id]['job_id'];
                }
            }
        }
        if($is_regular){//是否有转岗信息
            apf_require_class('Bll_Flow_UserRegular');
            $bll_regular = new Bll_Flow_UserRegular();
            $rg_flow_ids = array_keys($tmp_uids);
            $d_regular = $bll_regular->find_by_ids($rg_flow_ids);
            foreach($tmp_uids as $flow_id=>$uid){
                if(!empty($d_regular[$flow_id])){
                    $job_ids[$flow_id] = $d_regular[$flow_id]['job_id'];
                }
            }
        }

        if($is_renew){
            apf_require_class('Bll_Flow_UserRenew');
            $bll_renew = new Bll_Flow_UserRenew();
            $rn_flow_ids = array_keys($tmp_uids);
            $d_renew = $bll_renew->find_by_ids($rn_flow_ids);
            foreach($tmp_uids as $flow_id=>$uid){
                if(!empty($d_renew[$flow_id])){
                    $job_ids[$flow_id] = $d_renew[$flow_id]['job_id'];
                }
            }
        }
        apf_require_class('Bll_Hr_OutInterface');
        $bll = new Bll_Hr_OutInterface();
        if(!empty($tmp_uids)){
            $uids = array_values($tmp_uids);
            $tmp_user_data = $bll->get_user_by_ids($uids,0);
            foreach($tmp_uids as $flow_id=>$uid){
                $user_data[$flow_id]['code'] = $tmp_user_data[$uid]['code'];
                $user_data[$flow_id]['user_id'] = $tmp_user_data[$uid]['user_id'];
                $user_data[$flow_id]['name'] = $tmp_user_data[$uid]['name'];
            }
        }

        if(!empty($job_ids)){//获取职位信息
            $jobids = array_values($job_ids);
            $job_list = $bll->get_job_dep_infos($jobids);
            foreach($job_ids as $flow_id=>$jobid){
                $user_data[$flow_id]['job_name'] = $job_list[$jobid]['position_name'];
                $user_data[$flow_id]['department_id'] = $job_list[$jobid]['department_id'];
                $user_data[$flow_id]['department_name'] = $job_list[$jobid]['bu_name'].$job_list[$jobid]['department_name'];
                $user_data[$flow_id]['city_name']=$job_list[$jobid]['city_name'];
            }
        }

        if(!empty($new_uids)){//新入职用户
            apf_require_class('Bll_Flow_User');
            $user_bll = new Bll_Flow_User();
            $new_a_uids = array_keys($new_uids);
            $new_user = $user_bll->get_job_by_uids($new_a_uids);
            foreach($new_user as $uid=>$val){
                $flow_id = $new_uids[$uid];
                $user_data[$flow_id] = $val;
            }
        }
        return $user_data;
    }


    /**
    * 获取所有代办事项
    * @return array
     */
    private function _get_all_wait_todo() {
        $result = array();
        $startid = 0;
        $limit = 100;
        while (true) {
            $sql = "SELECT * FROM flow WHERE now_status = ? AND flow_id > ? ORDER BY flow_id asc,effect_date asc limit $limit";
            $tmp = $this->get_db_rows($sql, $this->read_db,array(1,$startid));
            if (empty($tmp)) {
                break;
              }
            $count = count($tmp);
            foreach ($tmp as $val) {
                $result[] = $val;
             }
            $startid = $tmp[$count - 1]['flow_id'];
         }
        return $result;
    }

        /**
         * 获得角色列表
         * @param unknown_type $user_id
         * @return multitype:
         */
        private function _get_role_list($user_id,$work_city_id){
            $return = array();
            $role_list = $this->bll_role->get_role_by_user_id($user_id);
            if(!$role_list){
                $return = array();
            }

            foreach($role_list as $row){
                $return[$row['role_type']][] = $row['city_id'];
            }
            //如果是apply_relation有表有数据主管权限
            if($this->_check_superior($user_id)){
                $return[Const_Flow::ROLE_SUPERIOR][] = $work_city_id;
            }
            //添加普通员工权限
            $return[Const_Flow::ROLE_STAFF][] = $work_city_id;
            //添加seo权限
            $ceo_uid = APF::get_instance()->get_config('ceo_uid');
            if($user_id == $ceo_uid){
                $return[Const_Flow::ROLE_CEO][] = $work_city_id;
            }
            return $return;
        }

        /**
         * 检测是否主管
         */
       private function _check_superior($user_id){
            $bll_rela = new Bll_Flow_ApplyRelation();
            $re = $this->bll_rela->is_super_count($user_id);
            if($re){
                return true;
            }
            return false;
        }

        /**
         * 生成邮件模板
        * @param array $data
        * @return string
         * **/
       private function _build_mail_template($data,$username) {
           $tdstyle = "border: 1px solid #C3D7DB;padding: 2px 3px;";
           $result = "Dear {$username}:<br><br>有以下事项需要处理，<a href='{$this->basedomain}/flow/'><span style='font-weight: bold;font-size:15px;'>去处理</span></a>：<br><br>
                   <table style='width:900px;font-size:11px;font-family: Sans,Verdana,Tahoma,Arial,Simsun;width:800px;border: 1px solid #C3D7DB;border-radius: 3px 3px 3px 3px;box-shadow: 1px 1px 5px #5D99A3;color: #294145;font-size: 11px;font-weight: bold;line-height: 20px;margin: 10px;min-width: 100px;padding: 3px 10px;'>
                   <tbody><tr><td>";
           $result .="<table style='border-collapse:collapse;cellpadding:0;cellspacing:0;border:1px solid #C3D7DB;width:100%;'>
                        <thread style='background: none repeat scroll 0 0 #DDEEEE;'>
                        <tr style='line-height: 18px;background-color:#DDEEEE;font-weight: bold;'>
                        <td style='{$tdstyle}' align='center'>生效时间</td><td width='80px' style='{$tdstyle}'>流程类型</td>
                        <td style='{$tdstyle}' align='center'>姓名</td>
                        <td style='{$tdstyle}' align='center'>工作城市</td>
                        <td style='{$tdstyle}' align='center'>部门-职位</td>
                        <td style='{$tdstyle}' align='center'>流程阶段</td>
                        <td style='{$tdstyle}' align='center'>操作</td></tr></thread>";
           $count = count($data['datalist']);
           $num = 0;
           $result .= "<tbody>";
           foreach ($data['datalist'] as $key => $val) {
                ++$num;
                $result .= "<tr><td style='{$tdstyle}'>{$val['effect_date']}</td>
                <td style='{$tdstyle}'>{$this->flowtype[$val['flow_type']]}</td>
                <td style='{$tdstyle}'>{$val['user_name']}</td>
                <td style='{$tdstyle}'>{$this->cities[$val['work_city_id']]['city_name']}</td>
                <td style='{$tdstyle}'>{$this->userinfo[$val['flow_id']]['department_name']} - {$this->userinfo[$val['flow_id']]['job_name']}</td>
                <td style='{$tdstyle}'>{$this->_build_opt_list($val['flow_role_list'], $val['flow_type'], $val['flow_opt'])}</td>";
                if ($num == 1) {
                    $result .="<td rowspan='{$count}' style='{$tdstyle}' align='center'><a href='{$this->basedomain}/flow/'>去办理</td></tr>";
                } else {
                    $result .="</tr>";
                }
            }
           $result .= "</tbody>";
           $result .= "</table>";
           $result .= "</td></tr></tbody></table>";
           $result .= "<br><br>以上<br><br>此邮件系统自动发送，请勿回复！<br><br>";
           return $result;
        }

    /**
     * 当前阶段还能操作的内容,格式化，对于招聘需要特殊处理
    * @param sting $data
     */
    private function _build_opt_list($flow_role,$flow_type,$flow_opt){
        $str = array();
        if(empty($flow_role)){
            return '';
        }
        $role_ids = explode(',',$flow_role);
        $role_list = Const_Flow::role_list();
        foreach($role_ids as $id){
            if($flow_data['flow_type']==Const_Flow::FLOW_TYPE_RECRUIT &&  $id==Const_Flow::ROLE_SUPERIOR){
                $str[] = $this->_show_recruit_stage($flow_data);
            }else{
                $str[] = $id==Const_Flow::ROLE_STAFF ? '交接资料' : $role_list[$id];
            }
        }
        return implode('-',$str);
    }

    /**
     * 权限能管理的城市
     * @return array
     */
    private function _get_city_list(){
        $proe_bll = new Bll_Hr_Property();
        $city_list = $proe_bll->get_city_list();
        return $city_list;
    }

    private function _get_flow_type(){
        return array(
                Const_Flow::FLOW_TYPE_ENTRY=>'入职',
                Const_Flow::FLOW_TYPE_TRANSFER=>'异动',
                Const_Flow::FLOW_TYPE_DIMISSION=>'离职',
                Const_Flow::FLOW_TYPE_MONEY => '异动',
                Const_Flow::FLOW_TYPE_RECRUIT=>'招聘',
                Const_Flow::FLOW_TYPE_REGULAR=>'转正',
                Const_Flow::FLOW_TYPE_RENEW=>'续签',
        );
    }

    private function _show_recruit_stage($flow_opt){
        $list = array(
                Const_Flow::PHASE_50=>'一级主管',
                Const_Flow::PHASE_51=>'二级主管',
                Const_Flow::PHASE_52=>'三级主管'
                );
        return $list[$flow_opt];
    }

}